package com.kzx.blog.util;

import com.kzx.blog.config.model.Constant;
import com.kzx.blog.config.model.FailedException;
import com.kzx.blog.config.model.FailedInfo;
import com.obs.services.ObsClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author kongz
 * @version 1.0 2021/12/9 17:24
 * @description 文件存储工具类
 */
@Component
public class OBSUtils {

    @Value("${huawei.obs.ak}")
    private String obsAk;

    @Value("${huawei.obs.sk}")
    private String obsSk;

    @Value("${huawei.obs.endpoint}")
    private String endpoint;

    @Value("${huawei.obs.bucket}")
    private String bucketName;

    /**
     * 上传文件
     * @param file 文件
     */
    public String uploadFile(MultipartFile file) {
        try (ObsClient obsClient = new ObsClient(obsAk, obsSk, endpoint)) {
            String fileName = getFileName(file.getContentType());
            obsClient.putObject(bucketName, fileName, file.getInputStream());
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
            throw new FailedException(FailedInfo.ERROR_UPLOAD.getErrorCode(), FailedInfo.ERROR_UPLOAD.getErrorMsg());
        }
    }

    /**
     * 生成文件名, 文件以时间戳命名
     * @param type 文件类型
     * @return 文件名
     */
    private static String getFileName(String type) {
        String[] split = type.split("/");

        if (split[0].equals("image")) {// 如果是图片格式
            return Constant.IMG_PATH + System.currentTimeMillis() + "." + split[1];
        }

        return "";
    }

}
